import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View} from '@tarojs/components'
import './wallet.scss'
import {user} from '../../utils/user.service'
import {http} from '../../utils/http'
import {RECHARGE_LIST} from '../../constants/api'
import {AtButton, AtInputNumber} from 'taro-ui'
import {WxUserInfo, ServerUserInfo} from 'src/utils/server.interface'
import {payment} from '../../utils/payment.service'
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"

interface RechargeList {
  name: string
}

interface RechargeData {
  name: string
  value: number
}

interface PageState {
  rechargeList: RechargeData[]
  userInfo: WxUserInfo & ServerUserInfo | false
  curValue: number
  selfPay?: number
}

export default class Recharge extends Component {
  state: PageState = {
    rechargeList: [],
    userInfo: false,
    curValue: 200,
    selfPay: 0,
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    }
    const userInfo: any = await Taro.getStorage({key: 'user'})
    const rechargeList = await http.get<RechargeList[]>(RECHARGE_LIST, {})
    if (rechargeList) {
      const newVal: RechargeData[] = rechargeList.map(item => {
        return {
          name: item.name,
          value: parseInt(item.name)
        }
      })
      this.setState({rechargeList: newVal, userInfo: userInfo.data.userInfo, curValue: newVal[0].value})
    }
  }

  itemSelect(value) {
    this.setState({curValue: value})
  }

  handleChange(val) {
    val = Math.floor(val);
    this.setState({selfPay: val})
  }

  async pay(): Promise<void> {
    const {curValue, selfPay} = this.state
    if (curValue > 0) {
      const payRet = await payment.rechargePayment(curValue)
      if (!payRet) {
        return
      } else {
        Taro.showToast({title: '充值成功', icon: 'success'})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.navigateBack({
            delta: 1
          })
        }, 1500)
      }
    } else if (curValue === -1) {
      const payRet = await payment.rechargePayment(selfPay)
      if (!payRet) {
        return
      } else {
        Taro.showToast({title: '充值成功', icon: 'success'})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.navigateBack({
            delta: 1
          })
        }, 1500)
      }
    } else {
      Taro.showToast({title: '请先选择一个金额', icon: 'none'})
    }
  }

  render() {
    const {rechargeList, curValue, selfPay} = this.state
    return (
      <View className='wallet-root recharge'>
        <GzhAuth />
        <View className='list-box'>
          {rechargeList.length > 0 && rechargeList.map(item => <View className='list-item'
            onClick={this.itemSelect.bind(this, item.value)}
          >
            <View className={`item ${curValue === item.value && 'active'}`}>
              {item.name}
            </View>
          </View>)}
        </View>
        <View className='self-pay'>
          <View className={`self-pay-left ${curValue === -1 && 'active'}`} onClick={this.itemSelect.bind(this, -1)}>
            自定义
          </View>
          {curValue === -1 && <View className='self-pay-right'>
            <AtInputNumber
              className='car-num-bag'
              min={0}
              max={999999999}
              step={1}
              width={200}
              value={selfPay}
              onChange={this.handleChange.bind(this)}
            />
          </View>}
        </View>
        <View style='width: 90%;'><AtButton type='primary' disabled={curValue == -1 && selfPay == 0}
          onClick={this.pay.bind(this)}
        >立即充值</AtButton></View>
      </View>
    )
  }
}
